package com.api.gateway.controller;

import com.api.gateway.exception.ArgumentCountException;
import com.api.gateway.exception.DigitalSignException;
import com.api.gateway.service.DecryptService;
import com.api.gateway.service.ValidationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

/**
 * Created by hao.g on 18/4/2.
 */
@RestController
public class GatewayController {
    private static final Logger LOGGER = LoggerFactory.getLogger(GatewayController.class);

    @Autowired
    private ValidationService validationService;

    @Autowired
    private DecryptService decryptService;

    @RequestMapping("/gateway")
    public void index(HttpServletRequest request) {
        Assert.notNull(request, "invalid http request");
        String[] params = request.getQueryString().split("&");
        try {
            //参数校验
            validationService.check(params);

            //解签
            String signCipher = decryptService.decryptSign(params[4]);

            //验签
            if (!decryptService.validateSign(params[3], signCipher)){
                throw new DigitalSignException("数字签名异常");
            }

            //解密
            String data = decryptService.decryptData(params[1], signCipher);
            LOGGER.info("解签解密完成");

        } catch (ArgumentCountException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (DigitalSignException e) {
            e.printStackTrace();
        }
    }
}
